# coding=utf-8
import os
from types import NoneType
from django.core.management import CommandError
from django.db import transaction
import time
from com.kjssoft.common.ant import XMLInitialHandler
from com.kjssoft.common.beehive.consts import GoodsConsts
from com.kjssoft.common.beehive.models import Goods, Category, GoodsProfile

try:
    from xml.etree import cElementTree as ET
except ImportError:
    from xml.etree import ElementTree as ET

__author__ = 'daihaibin'

class CategoryInitial(object):
    def __init__(self):
        self.model = None

class XMLInitialHandler(XMLInitialHandler):

    def __init__(self, initial_data_xml_path):
        if os.path.exists(initial_data_xml_path) and os.path.isfile(initial_data_xml_path):
            self.et_parser = ET.parse(initial_data_xml_path)
        else:
            raise CommandError('Original xml data can not be found.')

    def _parse_goods(self, element, goods_model):
        """
        解析物品基础属性的公共部分的数据
        """
        goods_model.uuid = element.find('uuid').text
        goods_model.name = element.find('name').text
        goods_model.description = element.find('description').text
        goods_model.create_ms = int(time.time())
        max = element.find('max')
        if not isinstance(max, NoneType):
            goods_model.max_size = max.text
        else:
            goods_model.max_size = GoodsConsts.MAX_SIZE_NO_LIMIT
        life = element.find('life')
        if not isinstance(life, NoneType):
            goods_model.life_cycle = life.text
        else:
            goods_model.life_cycle = GoodsConsts.LIFE_CYCLE_FOREVER

    def _parse_goods_categories(self, element):
        categories = []
        categories_element = element.find('gcategories')
        if categories_element and not isinstance(categories_element, NoneType):
            for c_uuid in categories_element:
                categories.append(c_uuid.text)
        return categories

    def _parse_goods_profile(self, prices_elements):
        prices = []
        if prices_elements:
            for price_element in prices_elements:
                price_dict = {}
                price_dict.update({'goods':price_element.find('goods').text})
                price_dict.update({'size':price_element.find('size').text})
                prices.append(price_dict)
        return prices

    def _parse_profile_goods_elements(self, elements):
        profile_goods = {}
        if not elements or isinstance(elements, NoneType):
            return profile_goods
        for profile_goods_element in elements:
            goods = {}
            goods_model = Goods()
            #解析物品元数据
            self._parse_goods(profile_goods_element, goods_model)
            goods.update({'model':goods_model})
            prices_element = profile_goods_element.find('prices')
            goods.update({'prices':self._parse_goods_profile(prices_element)})
            rewards_element = profile_goods_element.find('rewards')
            goods.update({'rewards':self._parse_goods_profile(rewards_element)})
            limits_element = profile_goods_element.find('limits')
            goods.update({'limits':self._parse_goods_profile(limits_element)})
            goods.update({'categories':self._parse_goods_categories(profile_goods_element)})
            goods_model.save()
            profile_goods.update({goods_model.uuid:goods})
        return profile_goods

    def _initial_clean(self):
        """
        更新数据前需要先清理数据，物品数据不允许清除
        清除的数据包括物品的价格，使用物品奖励设定以及使用物品限制设定，建筑物升级等级，物品的分类信息
        严格不允许修改物品uuid
        """
        #清除物品的分类信息,价格设定，奖励设定以及限制设定
        for g in Goods.objects.all():
            g.categories.all().delete()
            g.prices.all().delete()
            g.limits.all().delete()
            g.rewards.all().delete()

    def _parse_categories(self, category_elements):
        categories = {}
        if category_elements:
            for category_element in category_elements:
                category_model = Category()
                category_model.uuid = category_element.find('uuid').text
                category_model.name = category_element.find('name').text
                categories.update({category_model.uuid:category_model})
                category_model.save()
        return categories

    @transaction.commit_on_success
    def initial(self):
        #依赖关系清除
        self._initial_clean()
        #物品分类解析
        categories_elements = self.et_parser.find('Categories')
        categories = self._parse_categories(categories_elements)
        #属性类物品解析
        profile_goods = self._parse_profile_goods_elements(self.et_parser.find('Profiles'))
        #建筑类物品解析

        result = {}
        result.update(profile_goods)
        for value in result.values():
            model = value['model']
            #设置物品的分类
            for category in value['categories']:
                model.categories.add(categories.get(category))
            prices = value.get('prices')
            if prices:
                for price in prices:
                    profile = GoodsProfile()
                    profile.goods = result[price['goods']]['model']
                    profile.size = price['size']
                    profile.save()
                    model.prices.add(profile)
            rewards = value.get('rewards')
            if rewards:
                for reward in rewards:
                    profile = GoodsProfile()
                    profile.goods = result[reward['goods']]['model']
                    profile.size = reward['size']
                    profile.save()
                    model.rewards.add(profile)
            limits = value.get('limits')
            if limits:
                for limit in limits:
                    profile = GoodsProfile()
                    profile.goods = result[limit['goods']]['model']
                    profile.size = limit['size']
                    profile.save()
                    model.limits.add(profile)

